﻿using System;
using System.Net;
using System.IO;
using System.Xml.Linq;
using System.Xml.XPath;
using System.Collections.Generic;

namespace Reader
{
    public class BookLocation
    {
        public string Site
        { get; set; }
        public string BookName { get; set; }
        public string BookPage { get; set; }

    }
    public class LocalBookConfig
    {

        //public static readonly LocalBookConfig LoaclBook = new LocalBookConfig(ReaderPath.LocalFile);
        //public static readonly LocalBookConfig FavoriteBook = new LocalBookConfig(ReaderPath.FavoriteFile);
        public static readonly LocalBookConfig LoaclBook;
        public static readonly LocalBookConfig FavoriteBook;
        static LocalBookConfig()
        {
            if (App.Current.IsRunningOutOfBrowser)
            {
                LoaclBook = new LocalBookConfig(ReaderPath.LocalFile);
                FavoriteBook = new LocalBookConfig(ReaderPath.FavoriteFile);
            }
        }
        private readonly string configPath;
        public XDocument LocalBook { get; private set; }
       
        private LocalBookConfig(string configPath)
        {
            this.configPath = configPath;
            if (File.Exists(configPath))
            {
                LocalBook = XDocument.Parse(File.ReadAllText(configPath));
            }
            else
            {
                string t = "<?xml version='1.0' encoding='UTF-8'?><LocalBook></LocalBook>";
                File.WriteAllText(configPath, t);
                LocalBook = XDocument.Parse(t);                
            }
        }
        public void AddBook(string bookName, string bookPageUri)
        {
            bool x =bool.Parse(LocalBook.XPathEvaluate(string.Format("//Book='{0}'", bookPageUri)).ToString());
            if (x !=true)
            {
                LocalBook.Root.Add(new XElement("Book", new XAttribute("bookName", bookName), new XCData(bookPageUri)));
                Save();
            }
            
        }
        public List<BookLocation> GetBook()
        {
            List<BookLocation> books = new List<BookLocation>();
            foreach (XElement book in LocalBook.Descendants("Book"))
            {
                books.Add(new BookLocation() { BookName = (string)book.Attribute("bookName"), BookPage=book.Value,Site=new Uri(book.Value).Host });
            }
            return books;
        }
        private void Save()
        {
            File.WriteAllText(configPath, LocalBook.ToString());
        }

    }
}
